package com.dsx.config.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.dsx.entity.User;
import com.dsx.service.UserService;
import com.dsx.utils.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author dsx
 * @date 2021/3/30 20:06
 * @since JDK1.8
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;
    //让shiro不使用自己的usernamepasswordtoken,使用JwtToken
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权方法=AuthorizationInfo");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证方法=AuthenticationInfo");
        
        JwtToken jwtToken= (JwtToken) authenticationToken;
        //id放在Subject中
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        User dbUser = userService.getById(Long.valueOf(userId));
        if(dbUser==null){
            throw new AuthenticationException("用户名或密码错误，请重新输入！");
        }
        if(dbUser.getStatus()==-1){
            throw new LockedAccountException("账户被锁！请解除锁定！");
        }
        //这里传递的信息需要封装，防止私密信息泄露，所以需要封装一个类
        AccountProfile ap = new AccountProfile();
        //hutool封装的工具类
        BeanUtil.copyProperties(dbUser,ap);
        return new SimpleAuthenticationInfo(ap,jwtToken.getCredentials(),getName());
    }
}
